package cn.zhou.controller;

import cn.zhou.pojo.User;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/***
 * @RestController 一个顶俩
 */
//@Controller
@RestController
public class JsonDemo {
    @RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
    //@ResponseBody//跳过视图解析
    public String test() throws JsonProcessingException {
        User user = new User(1,"周周",18);
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(user);
        return  s.toString();
    }
    @RequestMapping(value = "/j2",produces = "application/json;charset=utf-8")
    public String test2() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        ArrayList<User> userlist = new ArrayList<>();
        User user1 = new User(1,"周周",18);
        User user2 = new User(1,"周周",18);
        User user3 = new User(1,"周周",18);
        User user4 = new User(1,"周周",18);
        userlist.add(user1);
        userlist.add(user2);
        userlist.add(user3);
        userlist.add(user4);
        String s = mapper.writeValueAsString(userlist);
        return s;
    }
    @RequestMapping(value = "/j3",produces = "application/json;charset=utf-8")
    public String test3() throws JsonProcessingException {
//        ObjectMapper mapper = new ObjectMapper();
//        Date date = new Date();
//        SimpleDateFormat sdf = new SimpleDateFormat();
//        String format = sdf.format(date);
//        String s = mapper.writeValueAsString(format);
        return  new ObjectMapper().writeValueAsString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

    @RequestMapping(value = "/j4",produces = "application/json;charset=utf-8")
    public String test4() throws JsonProcessingException {
        ArrayList<User> userlist = new ArrayList<>();
        User user1 = new User(1,"周周",18);
        User user2 = new User(1,"周周",18);
        User user3 = new User(1,"周周",18);
        User user4 = new User(1,"周周",18);
        userlist.add(user1);
        userlist.add(user2);
        userlist.add(user3);
        userlist.add(user4);
        /***
         * 阿里大法好
         */
        return JSON.toJSONString(userlist);
    }

}
